package com.heima.article.listen;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.service.ApArticleConfigService;
import com.heima.article.service.ApArticleService;
import com.heima.constants.message.NewsUpOrDownConstants;
import com.heima.constants.message.PublishArticleConstants;
import com.heima.model.article.pojos.ApArticleConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@Slf4j
public class PublishArticleListener {
    @Autowired
    private ApArticleService apArticleService;
    @Autowired
    private ApArticleConfigService apArticleConfigService;

    //监听文章审核通过通知,准备发布
    @RabbitListener(queuesToDeclare = {@Queue(value = PublishArticleConstants.PUBLISH_ARTICLE_QUEUE)})
    public void publishArticle(String newsId) {
        log.info("接收到发布文章通知， 待发布文章id: {} , 当前时间: {}", newsId, LocalDateTime.now().toString());
        try {
            apArticleService.publishArticle(Integer.valueOf(newsId));
            log.info("发布文章通知处理完毕  文章发布成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("发布文章通知处理失败， 文章未能成功发布 文章id: {} , 失败原因:{}", newsId, e.getMessage());
        }
    }

    //监听文章上架发来的消息,准备修改文章配置表  上架
    @RabbitListener(queuesToDeclare = {@Queue(value = NewsUpOrDownConstants.NEWS_UP_FOR_ARTICLE_CONFIG_QUEUE)})
    public void UpArticleConfig(String id) {
        log.info("接收到文章上架通知,待修改文章配置表,当前时间:{}",LocalDateTime.now().toString());
        LambdaUpdateWrapper<ApArticleConfig> wrapper = Wrappers.lambdaUpdate();
        wrapper.eq(ApArticleConfig::getArticleId,Long.valueOf(id));
        wrapper.set(ApArticleConfig::getIsDown,false);
        apArticleConfigService.update(wrapper);
        log.info("文章配置修改完成!");
    }

    //监听文章上架发来的消息,准备修改文章配置表  下架
    @RabbitListener(queuesToDeclare = {@Queue(value = NewsUpOrDownConstants.NEWS_DOWN_FOR_ARTICLE_CONFIG_QUEUE)})
    public void downArticleConfig(String id) {
        log.info("接收到文章下架通知,待修改文章配置表,当前时间:{}",LocalDateTime.now().toString());
        LambdaUpdateWrapper<ApArticleConfig> wrapper = Wrappers.lambdaUpdate();
        wrapper.eq(ApArticleConfig::getArticleId,Long.valueOf(id));
        wrapper.set(ApArticleConfig::getIsDown,true);
        apArticleConfigService.update(wrapper);
        log.info("文章配置修改完成!");
    }
}